<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org">
<head>
    <th:block th:include="include :: header('新增识别')"/>
    <script src="/sweetalert2-11.12.2/sweetalert2@11.js"></script>
</head>
<body class="white-bg">
<div class="wrapper wrapper-content animated fadeInRight ibox-content">
    <form class="form-horizontal m" id="form-predict-add">
        <div class="form-group">
            <label class="col-sm-3 control-label">识别任务名称：</label>
            <div class="col-sm-8">
                <input id="predictName" name="predictName" class="form-control" type="text" placeholder="任务名称">
            </div>
        </div>
        <div class="form-group" style="display: none">
            <label class="col-sm-3 control-label">所选训练任务的id：</label>
            <div class="col-sm-8">
                <input id="trainMissionId" name="trainMissionId" class="form-control" type="text">
            </div>
        </div>

        <div class="form-group">
            <label class="col-sm-3 control-label">所选训练任务的名称：</label>
            <div class="col-sm-8">
                <select id="trainMissionName" name="trainMissionName" class="form-control" type="text"></select>
            </div>
        </div>
        <div class="form-group" style="display: none">
            <label class="col-sm-3 control-label">所识别数据集的id：</label>
            <div class="col-sm-8">
                <input id="datasetId" name="datasetId" class="form-control" type="text">
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label">识别数据集名称：</label>
            <div class="col-sm-8">
                <select id="datasetName" name="datasetName" class="form-control" type="text"></select>
            </div>
        </div>
        <!--			<div class="form-group">	-->
        <!--				<label class="col-sm-3 control-label">识别状态：</label>-->
        <!--				<div class="col-sm-8">-->
        <!--					<input id="status" name="status" class="form-control" type="text">-->
        <!--				</div>-->
        <!--			</div>-->
        <!--			<div class="form-group">	-->
        <!--				<label class="col-sm-3 control-label">开始识别时间：</label>-->
        <!--				<div class="col-sm-8">-->
        <!--					<input id="beginTime" name="beginTime" class="form-control" type="text">-->
        <!--				</div>-->
        <!--			</div>-->
        <!--			<div class="form-group">	-->
        <!--				<label class="col-sm-3 control-label">结束识别时间：</label>-->
        <!--				<div class="col-sm-8">-->
        <!--					<input id="endTime" name="endTime" class="form-control" type="text">-->
        <!--				</div>-->
        <!--			</div>-->
    </form>
</div>
<div th:include="include::footer"></div>
<script type="text/javascript">
    var userId = null;
    var prefix = ctx + "deep_learning/predict"

    $.ajax({
        url: '/deep_learning/app01Dataset/currentUser', // 此地址返回当前用户的 userId
        method: 'GET',
        success: function (response) {
            userId = (response.userId);
        },
        error: function (xhr, status, error) {
            console.error('请求当前用户信息失败:', error);
        }
    });


    $("#form-predict-add").validate({
        rules: {
            xxxx: {
                required: true,
            },
        },
        focusCleanup: true
    });

    function submitHandler() {
        var predictMissionName = $('#predictName').val();
        if (predictMissionName === '' || predictMissionName === null) {
            predictMissionName = '识别任务'
        }
        console.log("predictMissionName: ", predictMissionName)
        $.ajax({
            url: prefix + "/checkTrainMissionName",
            type: "GET",
            data: {name: predictMissionName},
            success: function (response) {
                if (response) {
                    Swal.fire({
                        icon: 'error',
                        title: '错误',
                        text: '名称已存在，请使用其他名称',
                        showConfirmButton: true,
                        allowOutsideClick: false,
                        allowEscapeKey: false
                    });
                }
                else {


                    // 验证先前是否有此任务
                    $.ajax({
                        url: prefix + "/checkPredictMissionUnique",
                        type: "GET",
                        data: {
                            trainMissionId: $('#trainMissionId').val(),
                            datasetId: $('#datasetId').val(),
                            user_id: userId
                        },
                        success: function (response) {
                            if (response) {
                                // console.log("任务已存在，请勿重复添加")
                                Swal.fire({
                                    icon: 'error',
                                    title: '错误',
                                    text: '同样和训练模型和数据集已存在，请勿重复添加。',
                                    showConfirmButton: true,
                                    allowOutsideClick: false,
                                    allowEscapeKey: false
                                });
                            } else {
                                if ($.validate.form()) {
                                    $.operate.save(prefix + "/add", $('#form-predict-add').serialize());
                                }
                            }
                        },
                        error: function (xhr, status, error) {
                            Swal.fire({
                                icon: 'error',
                                title: '请求失败',
                                text: '检查任务名称失败，请稍后重试',
                                showConfirmButton: true,
                                allowOutsideClick: false,
                                allowEscapeKey: false
                            });
                        }
                    });


                }
            },
            error: function (xhr, status, error) {
                Swal.fire({
                    icon: 'error',
                    title: '请求失败',
                    text: '检查任务名称失败，请稍后重试',
                    showConfirmButton: true,
                    allowOutsideClick: false,
                    allowEscapeKey: false
                });
            }
        });
        window.parent.postMessage('refreshTable', '*');
    }
</script>
<script>
    $(document).ready(function () {
        let id = null;  // 模型id
        let name = null; // 模型名称
        let user_id = null;  //归属用户id
        let user = null;  //归属用户名

        let url = '/deep_learning/trainMission/selectDatasetAndUserNoAboutLabel';
        var currentUserId = $('#userId').val(); // 当前用户id
        if (currentUserId === 1) {
            url = '/deep_learning/App01Dataset/getList'
        }

        // 数据集---------------------------------------
        $.ajax({
            url: url,
            type: 'GET',
            processData: false,
            contentType: false,
            success: function (response) {
                // 假设响应是一个字符串数组
                let models = response;

                // 将每个元素解析为一个选项
                models.forEach(function (model) {
                    // 假设每个元素的格式为 "id|name|version|user"
                    let parts = model.split('|');
                    id = parts[0];  // 模型id
                    name = parts[1]; // 模型名称
                    user_id = parts[2];  //归属用户id
                    user = parts[3];  //归属用户名

                    // 创建选项元素，将id存储在value中，将user_id存储在data-user-id属性中
                    let option = new Option(`${name} ------- 归属用户：${user}`, name);
                    // console.log('user_id：'+user_id)
                    option.setAttribute('data-user-id', user_id);
                    option.setAttribute('data-datasetTrain-id', id)
                    $('#datasetName').append(option);


                });
                // 设置默认选中第一个选项
                if (models.length > 0) {
                    // console.log('models[0].split(\'|\')[0]：'+models[0].split('|')[0])
                    $('#datasetId').val(models[0].split('|')[0]); // 假设第一个元素的id是第一个分割项
                }
                document.getElementById('datasetName').addEventListener('change', function () {
                    // console.log('this.value：'+this.value)
                    let selectedId = this.options[this.selectedIndex].getAttribute('data-datasetTrain-id');  // 获取id
                    let selectedOption = this.options[this.selectedIndex];
                    let selectedUserId = this.options[this.selectedIndex].getAttribute('data-user-id'); // 获取user_id
                    // console.log(`Selected DatasetTrain ID: ${selectedId}, User ID: ${selectedUserId}`);
                    // 	表单赋值
                    // console.log('selectedId：'+selectedId)
                    $('#datasetId').val(selectedId);
                    // console.log(selectedOption.text)
                    // $('#datasetName').val(selectedOption.text.split(' ------- ')[0])  //

                });
            },
            error: function (xhr, status, error) {
                let errorMessage = "请求失败，发生未知错误。";

                if (xhr.responseJSON && xhr.responseJSON.message) {
                    errorMessage = xhr.responseJSON.message;
                } else if (xhr.responseText) {
                    try {
                        const jsonResponse = JSON.parse(xhr.responseText);
                        if (jsonResponse.message) {
                            errorMessage = jsonResponse.message;
                        } else {
                            errorMessage = xhr.responseText;
                        }
                    } catch (e) {
                        errorMessage = xhr.responseText;
                    }
                }
                Swal.fire({
                    icon: 'error',
                    title: '请求失败',
                    text: '错误信息: ' + errorMessage,
                    showConfirmButton: true,
                    allowOutsideClick: false,
                    allowEscapeKey: false
                });
            }
        });
        // 	---------------------------------------------------------------------添加当前登录用户的id
        $.ajax({
            url: '/deep_learning/app01Dataset/currentUser', // 此地址返回当前用户的 userId
            method: 'GET',
            success: function (response) {
                $('#userId').val(response.userId);
            },
            error: function (xhr, status, error) {
                console.error('请求当前用户信息失败:', error);
            }
        });
    });

    $(document).ready(function () {
        // 发起 AJAX 请求获取 TrainMission 列表
        $.ajax({
            url: '/deep_learning/trainMission/getFinishedTrainMissionList',
            type: 'GET',
            dataType: 'json',
            success: function (response) {
                if (Array.isArray(response)) {
                    console.log('训练任务列表:', response);
                    // 解析并处理数据
                    populateSelectWithTrainMissions(response);
                } else {
                    console.error('返回数据格式不正确:', response);
                    alert('获取的训练任务数据格式不正确。');
                }
            },
            error: function () {
                alert('无法获取训练任务数据。');
            }
        });

        // 将 TrainMission 列表添加到 <select> 元素中
        function populateSelectWithTrainMissions(trainMissions) {
            var selectElement = $('#trainMissionName');
            var trainMissionIdElement = $('#trainMissionId');
            // 清空现有选项
            selectElement.empty();
            // 遍历每个 TrainMission 对象
            trainMissions.forEach(function (trainMission, index) {
                var optionValue = trainMission.trainMissionName;
                var optionElement = $('<option></option>').attr('value', optionValue).text(trainMission.trainMissionName + ' ------- 归属用户：' + trainMission.userName);
                // 给optionElement添加id属性，以便在change事件中获取id
                optionElement.attr('id', trainMission.id);
                selectElement.append(optionElement);

                // 默认选中第一个元素并设置 trainMissionId
                if (index === 0) {
                    selectElement.val(trainMission.trainMissionName);
                    trainMissionIdElement.val(trainMission.id);
                }
            });

            // 监听选择变化,id自动填充
            selectElement.on('change', function () {
                var selectedOption = this.options[this.selectedIndex];
                var selectedValue = selectedOption.id;
                console.log(selectedOption)
                trainMissionIdElement.val(selectedValue);
            });
        }

    });

</script>
</body>
</html>
